﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Espam.Idiomas.Decimo.Tesis.Negocio;
using Microsoft.Reporting.WebForms;

namespace Espam.Idiomas.Decimo.Tesis.Web
{
    public partial class UI_Exonerated : System.Web.UI.Page
    {
        string validaSession = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
                Response.Cache.SetAllowResponseInBrowserHistory(false);
                Response.Cache.SetNoStore();

                if (Session["userEspamIdiomasVarSession001"] == null || Session["rolEspamIdiomasVarSession003"] == null)
                {
                    validaSession = "NoHaIniciadoSession";
                    Response.Redirect("UI_Login.aspx?validaSession=" + validaSession);
                }
                else if (Session["userEspamIdiomasVarSession001"] != null && Session["rolEspamIdiomasVarSession003"].ToString() == "Docente")
                {
                    Response.Redirect("UI_DashboardTeacher.aspx");
                }
                else if (Session["userEspamIdiomasVarSession001"] != null && Session["rolEspamIdiomasVarSession003"].ToString() == "Administradores")
                {

                    MaintainScrollPositionOnPostBack = true;
                   
                    //  btnGenerarReporte.Attributes.Add("onclick", " this.disabled = true,this.value='Procesando...'; " + ClientScript.GetPostBackEventReference(btnGenerarReporte, null) + ";");

                }
                else if (Session["userEspamIdiomasVarSession001"] != null && Session["rolEspamIdiomasVarSession003"].ToString() == "Alumno")
                {
                    Response.Redirect("UI_DashboardStudents.aspx");
                }
            }
            else
            {
                MaintainScrollPositionOnPostBack = true;
            }
        }

        private void cargarGrid()
        {
            Usuarios oUsuarios = new Usuarios();
            List<Usuarios> lista = new List<Usuarios>();
            oUsuarios.fechaInicio = DateTime.Parse(txtFechaInicio.Text);
            oUsuarios.fechaFin = DateTime.Parse(txtFechaFin.Text);
             lista = oUsuarios.GetExonerados();
            if (lista.Count > 0)
            {
                gvDocentes.DataSource = lista;
                gvDocentes.DataBind();
                btnGenerarReporte.Text = "Exportar a pdf";
            }
            else
            {
                gvDocentes.DataSource = lista;
                gvDocentes.DataBind();
                btnGenerarReporte.Text = "Generar Reporte";
            }
        }

        protected void btnGenerarReporte_Click(object sender, EventArgs e)
        {
            DateTime salida;
            if (DateTime.TryParse(txtFechaInicio.Text,out salida) && DateTime.TryParse(txtFechaFin.Text, out salida))
            {
                if (btnGenerarReporte.Text == "Generar Reporte")
                {
                    cargarGrid();
                    if (gvDocentes.Rows.Count > 0)
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Dttable", String.Format("CargaDataTable('{0}',{1});", "Contenido_gvDocentes", gvDocentes.Rows[0].Cells.Count), true);

                }
                else
                {
                    btnGenerarReporte.Text = "Generar Reporte";
                    CrearReporte();
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, GetType(), "MostarMensaje", "mensajeMal('ERRO!! REVISE EL FORMATO DE LA FECHA')", true);
            }
                        
        }

        private void CrearReporte()
        {

            EspamIdiomasDataSet.sp_getExoneradosReortDataTable dt = new EspamIdiomasDataSet.sp_getExoneradosReortDataTable();
            EspamIdiomasDataSetTableAdapters.sp_getExoneradosReortTableAdapter da = new EspamIdiomasDataSetTableAdapters.sp_getExoneradosReortTableAdapter();
            da.Fill(dt, DateTime.Parse(txtFechaInicio.Text), DateTime.Parse(txtFechaFin.Text));

            ReportViewer viewer = new ReportViewer();
            ReportDataSource RD = new ReportDataSource();
            RD.Value = dt;
            RD.Name = "DataSet1";
            //viewer.LocalReport.ReportPath = Server.MapPath("Reports/Administradores/Egresados.rdlc");
            viewer.LocalReport.DataSources.Clear();
            viewer.LocalReport.DataSources.Add(RD);
            //viewer.LocalReport.ReportEmbeddedResource = "Egresados.rdlc";
            viewer.LocalReport.ReportPath = Server.MapPath("Reports/Administradores/ExoneradosReport.rdlc");
            viewer.LocalReport.Refresh();

            string mimeType;
            string encoding;
            string fileNameExtension;
            string[] streams;
            Warning[] warnings;
            byte[] pdfContent = viewer.LocalReport.Render("PDF", string.Empty, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);

            this.Response.Clear();
            this.Response.ContentType = "application/pdf";
            this.Response.AddHeader("Content-disposition", "attachment; filename=ExoneradosReport.pdf");
            this.Response.BinaryWrite(pdfContent);
            this.Response.End();

        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            Response.Redirect("UI_Exonerated.aspx");
        }

        protected void gvDocentes_Load(object sender, EventArgs e)
        {
            if (gvDocentes.Rows.Count > 0)
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Dttable", String.Format("CargaDataTable('{0}',{1});", "Contenido_gvDocentes", gvDocentes.Rows[0].Cells.Count), true);
        }

        protected void gvDocentes_PreRender(object sender, EventArgs e)
        {
            GridView gvDocentes = (sender) as GridView;
            if (gvDocentes.Rows.Count > 0)
            {
                //This replaces <td> with <th> and adds the scope attribute
                gvDocentes.UseAccessibleHeader = true;

                //This will add the <thead> and <tbody> elements
                gvDocentes.HeaderRow.TableSection = TableRowSection.TableHeader;

                //This adds the <tfoot> element. 
                //Remove if you don't have a footer row
                gvDocentes.FooterRow.TableSection = TableRowSection.TableFooter;
            }
        }

        
        protected void btnDelete_Click(object sender, EventArgs e)
        {

            Usuarios oUsu = new Usuarios();
            string mensaje = "";
            oUsu.idExonerado = int.Parse(HfDeleteID.Value);
            mensaje = oUsu.EliminarExonerado();
            if (mensaje == "ELIMINADO CORRECTAMENTE")
            {
                ScriptManager.RegisterStartupScript(this.Page, GetType(), "MostarMensaje", "mensajeBien('EXONERADO ELIMINADO CORRECTAMENTE')", true);
                cargarGrid();

            }
            else
            {
                ScriptManager.RegisterStartupScript(this.Page, GetType(), "MostarMensaje", "mensajeMal('ERROR!! CUANDO INTENTO ELIMINAR EXONERADO REVISE ERRORES')", true);
                cargarGrid();
            }
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"<script type='text/javascript'>");
            //sb.Append("alert('Realizado Correctamente');");
            sb.Append("$('#flexModal').modal('hide');");
            sb.Append(@"</script>");
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "delHideModalScript", sb.ToString(), false);
        }

        protected void gvDocentes_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = Convert.ToInt32(e.CommandArgument);
            string id = gvDocentes.DataKeys[index].Value.ToString();
            HfDeleteID.Value = id;
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);

        }
    }
}